#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

"""
@File    : poll.py
@Author  : Link
@Time    : 2022/6/4 14:40
@Mark    : 
"""
import datetime as dt

from PySide2.QtGui import QGuiApplication, QCloseEvent, QResizeEvent
from PySide2.QtWidgets import QWidget, QLayout, QMainWindow
from pyqtgraph.dockarea import DockArea, Dock

from chart_core.chart_pyqtgraph.gui.line_chart import Ui_Form
from chart_core.chart_pyqtgraph.gui.ui_chart_window import Ui_MainWindow
from chart_core.chart_pyqtgraph.histogram import HistogramChart
from chart_core.chart_pyqtgraph.trans_bar import TransBarChart
from chart_core.chart_pyqtgraph.trans_scatter import TransScatterChart
from chart_core.chart_pyqtgraph.visual_map import VisualMapChart


def clearLayout(layout: QLayout):
    for i in range(layout.count()):
        layout.itemAt(i).widget().deleteLater()


class ChartsUi(QWidget, Ui_Form):
    temp = None

    def __init__(self, parent=None):
        super(ChartsUi, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle("绘图区")
        self.pushButton.pressed.connect(self.save_widget_pix)
        self.c_type = None
        self.scale = 1.0
        self.child_max_width = 1000

    def set_data(self, li, test_text: list, kwargs: dict, c_type: str):
        if not test_text:
            return
        self.temp = list()
        width = len(test_text)
        self.c_type = c_type
        if self.c_type != 'visual_map':
            self.widget.setFixedHeight(width * kwargs["绘图固定高度"])
        else:
            self.widget.setFixedHeight(width * kwargs["绘图最大宽度"] * 0.93)
        li.limit = kwargs["绘图值筛选区间"]
        li.rig = kwargs["Average_Sigma±区间"]
        self.scale = kwargs["绘图固定高度"] / kwargs["绘图最大宽度"]
        self.child_max_width = kwargs["绘图最大宽度"]

        for each in test_text:
            plot = None
            if self.c_type == 'trans_bar':
                plot = TransBarChart()
                plot.set_bins(kwargs["分布图柱子数量"])
                plot.set_li(li)
                plot.set_data(key=each)
                plot.set_range_self()
                plot.set_front_df_chart()
                plot.set_chart_df_chart()
                plot.set_line_self()
                plot.init_movable_line()
                self.verticalLayout.addWidget(plot.widget(kwargs["绘图最大宽度"]))
            if self.c_type == 'comparing':
                plot = HistogramChart()
                plot.set_li(li)
                plot.set_data(key=each)
                plot.set_range_self()
                plot.set_front_df_chart()
                plot.set_line_self()
                self.verticalLayout.addWidget(plot.widget(kwargs["绘图最大宽度"]))
            if self.c_type == 'scatter':
                plot = TransScatterChart()
                plot.set_li(li)
                plot.set_data(key=each)
                plot.set_range_self()
                plot.set_front_df_chart()
                plot.set_line_self()
                plot.init_movable_line()
                self.verticalLayout.addWidget(plot.widget(kwargs["绘图最大宽度"]))
            if self.c_type == 'visual_map':
                plot = VisualMapChart()
                plot.set_li(li)
                plot.set_data(key=each)
                plot.init_coord()
                plot.set_chart_df_chart()
                self.verticalLayout.addWidget(plot.widget())

            if plot is None:
                return

            self.temp.append(plot)

    def resize_update(self, width):
        if self.c_type == "visual_map":
            height = width * 0.93
        else:
            height = width * self.scale
        for each in self.temp:  # type:QWidget
            each.resize(width, height)
        self.widget.setFixedHeight(height * len(self.temp))

    def clear(self):
        if self.temp is None:
            return
        for each in self.temp:
            each.close_s()
        self.temp = None
        clearLayout(self.verticalLayout)

    def save_widget_pix(self):
        try:
            pixmap = QWidget.grab(self.widget)
            QGuiApplication.clipboard().setPixmap(pixmap)
            # filename = QFileDialog.getSaveFileName(self, caption='保存成图片', filter='png(*.png);;jpg(*.jpg)')
            # save_file = filename[0]
            # pixmap.save(save_file)
            self.setWindowTitle("已将Image复制到剪贴板@" + dt.datetime.now().strftime("%H:%M:%S"))
        except Exception as err:
            self.setWindowTitle(repr(err))

    def closeEvent(self, event: QCloseEvent) -> None:
        self.clear()
        super(ChartsUi, self).closeEvent(event)

    def resizeEvent(self, a0: QResizeEvent) -> None:
        if self.temp is None:
            pass
        else:
            width = a0.size().width()
            if self.c_type == "visual_map":
                self.resize_update(width)
            elif width < self.child_max_width:
                self.resize_update(width)
        super(ChartsUi, self).resizeEvent(a0)


class HideDock(Dock):

    def close(self):
        self.hide()


class ChartDockWindow(QMainWindow, Ui_MainWindow):
    """
    停靠ChartsUi
    TODO:
        1. 一个MDI只有一个ChartDockWindow
        2. 提前规划好
    """

    def __init__(self, parent=None, icon=None, space_nm=1):
        super(ChartDockWindow, self).__init__(parent)
        self.setupUi(self)
        self.parent = parent
        self.space_nm = space_nm
        if icon is not None:
            self.setWindowIcon(icon)
        self.title = "载入空间: {} -> Chart Widget".format(space_nm)
        self.setWindowTitle(self.title)
        self.area = DockArea()
        self.setCentralWidget(self.area)

        """ 暂时先定义四个位置, 来容纳四种图形, 反正这个是不常用的 """

        self.qt_distribution = ChartsUi(self)
        self.dock_qt_distribution = HideDock("横向分布图", size=(250, 400), closable=True)
        self.dock_qt_distribution.addWidget(self.qt_distribution)
        self.area.addDock(self.dock_qt_distribution)

        self.qt_visual_map = ChartsUi(self)
        self.dock_qt_visual_map = HideDock("参数性Map", size=(300, 400), closable=True)
        self.dock_qt_visual_map.addWidget(self.qt_visual_map)
        self.area.addDock(self.dock_qt_visual_map, "right", self.dock_qt_distribution)

        self.qt_scatter = ChartsUi(self)
        self.dock_qt_scatter = HideDock("散点图", size=(250, 400), closable=True)
        self.dock_qt_scatter.addWidget(self.qt_scatter)
        self.area.addDock(self.dock_qt_scatter, "right", self.dock_qt_distribution)

        self.dock_qt_distribution.hide()
        self.dock_qt_visual_map.hide()
        self.dock_qt_scatter.hide()

    def clear(self):
        self.parent = None
        self.qt_distribution.clear()
        self.qt_visual_map.clear()
        self.qt_scatter.clear()
        self.qt_distribution.deleteLater()
        self.qt_visual_map.deleteLater()
        self.qt_scatter.deleteLater()


if __name__ == '__main__':
    import sys
    from PySide2.QtWidgets import QApplication

    app = QApplication(sys.argv)
    win = ChartDockWindow()
    win.show()
    sys.exit(app.exec_())
